<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/head :: head(links)"/>


<script charset="utf-8" src="https://map.qq.com/api/gljs?libraries=tools&v=1.exp&key=L2DBZ-UK33U-HLGVI-42B2I-7COMK-RBB43"></script>
<style type="text/css">
    .layui-card-body {
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

    #map-container {
        width: 100%;
        height: 80%;
        position: relative;
    }

    #toolControl {
        position: absolute;
        top: 10px;
        left: 0px;
        right: 0px;
        margin: auto;
        width: 126px;
        z-index: 1001;
    }

    .toolItem {
        width: 30px;
        height: 30px;
        float: left;
        margin: 1px;
        padding: 4px;
        border-radius: 3px;
        background-size: 30px 30px;
        background-position: 4px 4px;
        background-repeat: no-repeat;
        box-shadow: 0 1px 2px 0 #E4E7EF;
        background-color: #ffffff;
        border: 1px solid #ffffff;
    }

    .toolItem:hover {
        border-color: #789CFF;
    }

    .active {
        border-color: #D5DFF2;
        background-color: #D5DFF2;
    }

    #polygon {
        background-image: url('/images/polygon.png');
    }

    #delete {
        background-image: url('/images/delete.png');
    }
</style>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 5px;">
            <span style="color: red;">操作指南：</span><br />
            绘制：鼠标点击顶部多边形，激活绘制，双击绘制完成<br />
            选择：鼠标左键点击图形<br />
            删除：选中图形后点击头部删除按钮可删除图形<br />
            编辑：选中图形后出现编辑点，拖动编辑点可移动顶点位置，双击实心编辑点可删除顶点<br />
        </div>
        <div class="layui-card-body">
            <div id="map-container"></div>
            <div id="toolControl">
                <!--<div class="toolItem" id="marker" title="标注" onclick="drawShape('marker');"></div>-->
                <div class="toolItem" id="polygon" title="多边形" onclick="drawShape('polygon');"></div>
                <!--<div class="toolItem" id="circle" title="圆形" onclick="drawShape('circle');"></div>-->
                <div class=" toolItem" id="delete" onclick="editor.delete();" title="删除"></div>
            </div>
            <div>

            </div>
        </div>
    </div>

</div>

<script src="/js/jquery-3.2.1.js"></script>

<script type="text/javascript">
    function getQueryParam(param) {
        var urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }
   let id='';

    $(document).ready(function () {
        var height = window.innerHeight;
        $("#map-container").css({"height":(height-120)+"px"});
         id=getQueryParam('id');
        //获取之前的数据
        $.post("/car/parkManage/getSiteInfo",{
            id:id
        },function (res) {
            console.log(res);

            if(res.data.points == null){
                initMap('');
                return false;
            }
            var r_id =id;
            var r_points = res.data.points;
            var pointsArr = JSON.parse(r_points);
            console.log("------------")
            console.log(pointsArr);
            console.log("------------")
            //初始化地图
            initMap({id:r_id,paths:pointsArr});

        });

      //  initMap({id:1,paths:{}});

    });

    var map, editor, shape;

    function drawShape(e) {
        console.log("drawPolygon!!: ", e)
        shape = e
        document.getElementById(shape).className = "toolItem active";
        editor.setActiveOverlay(shape)
        editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.DRAW);
    }

    function initMap(regionArr) {
        // 初始化地图
        map = new TMap.Map("map-container", {
            zoom: 17, // 设置地图缩放级别
            center: new TMap.LatLng(39.170959,116.94557399999997) // 设置地图中心点坐标
        });

        console.log(regionArr);
        var pointsArray = [];
        var r_id = '';
        if(regionArr != ''){
            // r_id = regionArr.r_id;
            r_id = regionArr.id;
            //for处理地图
            var pointsObj = regionArr.paths;
            for(var i=0; i<pointsObj.length; i++){
                pointsArray[i] = new TMap.LatLng(pointsObj[i].lat, pointsObj[i].lng);
            }
        }

        // 初始化几何图形及编辑器
        editor = new TMap.tools.GeometryEditor({
            map:map, // 编辑器绑定的地图对象
            overlayList: [ // 可编辑图层
                {
                    overlay: new TMap.MultiPolygon({
                        map:map,
                        styles: {
                            highlight: new TMap.PolygonStyle({
                                color: 'rgba(255, 255, 0, 0.6)'
                            }),
                            highlight2: new TMap.PolygonStyle({
                                color: 'rgba(255, 0, 0, 0.6)'
                            })
                        },
                        geometries: [
                            {
                                id: r_id,
                                paths: pointsArray
                            }
                        ]
                    }),
                    id: 'polygon',
                    selectedStyleId: 'highlight'
                }
            ],
            actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
            activeOverlayId: 'polygon', // 激活图层
            selectable: true, // 开启点选功能
            snappable: true // 开启吸附
        });

        // 监听绘制结束事件，获取绘制几何图形
        editor.on('draw_complete', function (geometry) {
            document.getElementById(shape).className = "toolItem";
            editor.setActionMode(TMap.tools.constants.EDITOR_ACTION.INTERACT);

            //准备请求添加接口
            var geometryData = {
                id:id,
                center:JSON.stringify(calculateCenter(geometry.paths)),
                points:JSON.stringify(geometry.paths)
            };
            ajaxUpdate(geometryData);
            //删除onclkick
            $("#polygon").removeAttr("onclick");
        });

        // 监听编辑
        editor.on('adjust_complete', function (evtResult) {

            var geometryData = {
                id:id,
                center:JSON.stringify(calculateCenter(evtResult.paths)),
                points:JSON.stringify(evtResult.paths)
            };
            ajaxUpdate(geometryData);
        });
        // 监听删除
        editor.on('delete_complete', function (evtResult) {

            var geometryData = {
                id:id,
                center:'',
                points:''
            };
            ajaxUpdate(geometryData);
            //添加onclkick
            $("#polygon").attr("onclick","drawShape('polygon');");
        });
    }



    /**文本标记获取
     function getText() {
        var textArr = [{
            'id': 'label_1', //点图形数据的标志信息
            'styleId': 'label', //样式id
            'position': new TMap.LatLng(36.08718923098989,111.51922298235638), //标注点位置
            'content': '腾讯北京总部', //标注文本
        }];

        //文本标记
        var label = new TMap.MultiLabel({
            id: 'label-layer',
            map: map, //设置折线图层显示到哪个地图实例中
            //文字标记样式
            styles: {
                'label': new TMap.LabelStyle({
                    'color': '#3777FF',
                    'size': 18
                })
            },
            //文字标记数据
            geometries: textArr
        });
    }*/

    //获取区域中心
    function calculateCenter(lnglatarr){
        var total = lnglatarr.length;
        var X=0,Y=0,Z=0;
        $.each(lnglatarr, function(index, lnglat) {
            var lng = lnglat.lng * Math.PI / 180;
            var lat = lnglat.lat * Math.PI / 180;
            var x,y,z;
            x = Math.cos(lat) * Math.cos(lng);
            y = Math.cos(lat) * Math.sin(lng);
            z = Math.sin(lat);
            X += x;
            Y += y;
            Z += z;
        });

        X = X/total;
        Y = Y/total;
        Z = Z/total;

        var Lng = Math.atan2(Y,X);
        var Hyp = Math.sqrt(X*X + Y*Y);
        var Lat = Math.atan2(Z,Hyp);

        return {lat:Lat*180/Math.PI, lng:Lng*180/Math.PI};
    };

    function ajaxUpdate(objData) {
        $.post("/car/parkManage/updateById",objData,function (res) {
            console.log(res);
        });
    }




</script>
